/**
 * Created by 白雨浓 on 2018/1/14 11:50.
 */
import Sequelize from 'sequelize';

export default {
    install(Vue){
        const self = Vue.prototype;

        let sequelize;

        const init = () => {
            if (sequelize) return;
            const config = self.$storage.local.getItem('config');
            const ac = config.list[config.active];

            sequelize = new Sequelize(ac.dbName, ac.dbUser, ac.dbPass, {
                host: ac.dbUrl.split(':')[0],
                port: ac.dbUrl.split(':')[1] !== '' ? ac.dbUrl.split(':')[1] : 3306,
                dialect: 'mysql',
                pool: {
                    max: 5,
                    min: 0,
                    idle: 30000
                }
            });
        };

        const conn = () => {
            init();
            return sequelize;
        };

        const query = (sql) => {
            const loading = self.$loading({
                lock: true,
                text: '数据库加载中……',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, .5)'
            });

            init();

            return new Promise((resolve, reject) => {
                sequelize.query(sql, {type: sequelize.QueryTypes.SELECT})
                    .then(data => {
                        loading.close();
                        resolve(data)
                    })
                    .catch(err => {
                        loading.close();
                        self.$alert(err);
                        reject(err);
                    });
            })
        };

        Vue.prototype.$db = {
            init,
            conn,
            sequelize,
            query,
        }
    }
}